package com.gx.auth.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.gx.auth.dao.RoleInterfaceDAO;
import com.gx.auth.entity.Role;

public class RoleInterfaceImplDAO implements RoleInterfaceDAO{
	private  Connection conn = null;
	
	
	public RoleInterfaceImplDAO(Connection conn) {
		this.conn = conn;
	}
	@Override
	public int insert(Role t) throws SQLException {
		String sql = "insert into auth_role (r_name,createtime,updatetime) values (?,datetime('now', 'localtime'),datetime('now', 'localtime')) ";
		PreparedStatement pst = conn.prepareStatement(sql);
		pst.setString(1, t.getRname());
		int count  = pst.executeUpdate();
		pst.close();
		return count;
	}

	@Override
	public int delete(Role t) throws SQLException {
		String sql = "delete from auth_role where r_name = ?";
		PreparedStatement pst = conn.prepareStatement(sql);
		pst.setString(1, t.getRname());
		int count  = pst.executeUpdate();
		pst.close();
		return count;
	}

	@Override
	public int update(Role t) {
		return 0;
	}

	@Override
	public List<Role> queryAll() throws SQLException {
		List<Role> ls = new ArrayList<>();
		String sql = "select * from auth_role ";
		PreparedStatement pst = conn.prepareStatement(sql);
		ResultSet rs = pst.executeQuery();
		while (rs.next()) {
			ls.add(saveResult(rs));
		}
		rs.close();
		pst.close();
		return ls;
	}

	@Override
	public Role query(String name) throws SQLException {
		Role role = new Role();
		String sql = "select * from auth_role where  r_name = ?";
		PreparedStatement pst = conn.prepareStatement(sql);
		pst.setString(1, name);
		ResultSet rs = pst.executeQuery();
		//判断是否为空
		if(rs.next()){
			role = saveResult(rs);
		}
		pst.close();
		return role;
	}
	@Override
	public Role saveResult(ResultSet rs) throws SQLException {
		Role role = new Role();
		role.setRid(new Integer(rs.getInt("r_id")));
		role.setRname(rs.getString("r_name"));
		role.setCreatetime(rs.getString("createtime"));
		role.setUpdatetime(rs.getString("updatetime"));
		return role;
	}

}
